package solution;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-18
 * Time: 15:46
 */
public class Solution4 {
    public static void main(String[] args) {
        String s = "I am a student";
        System.out.println(reverseSentence(s));
    }
    //字符串逆置，如 "I am a student" 逆置为 "student a am I"
    public static String reverseSentence(String str) {
        char[] arr = str.toCharArray();
        reserve(arr, 0, arr.length - 1);
        str = String.copyValueOf(arr);
        String[] strs = str.split(" ");
        StringBuilder strBuilder = new StringBuilder();
        for (String s : strs) {
            arr = s.toCharArray();
            reserve(arr, 0, arr.length - 1);
            strBuilder.append(String.copyValueOf(arr)).append(" ");
        }
        str = strBuilder.toString();
        str = str.substring(0, str.length() - 1);
        return str;
    }

    public static void reserve(char[] arr, int left, int right) {
        while (left < right) {
            char temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }

}
